package com.xywang.controller;

import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import com.xywang.pojo.User;
import com.xywang.service.user.UserService;
import com.xywang.util.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/jsp")
public class UserPwdController {
    private UserService userServiceImpl;
    @Autowired
    public void setUserServiceImpl(UserService userServiceImpl) {
        this.userServiceImpl = userServiceImpl;
    }

    // 跳转到修改密码的页面
    @RequestMapping("/toPwdModify")
    public String toPwdModify(){
        return "pwdModify";
    }

    @RequestMapping("/pwdModify")
    @ResponseBody
    public String pwdmodify(String oldpassword,HttpSession session){
        // 从session拿user对象，从表单拿输入的旧密码，创建哈希图存结果，转换为json的
        // 形式，以key--values键值对的形式，作为json数据流写到前端，前端js文件通过
        // result 取到值，再做判断
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        Map<String, String> resultMap = new HashMap<String, String>();

        if(user==null){
            //Session失效了 或 session过期了
            resultMap.put("result","sessionerror");
        }else if(StringUtils.isNullOrEmpty(oldpassword)){
            // 旧密码为空
            resultMap.put("result","error");
        }else{
            String userPassword = user.getUserPassword();
            if(oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else{
                resultMap.put("result","false");
            }
        }
        return JSONArray.toJSONString(resultMap);
    }
    @RequestMapping("/savePwd")
    public String savePwd(String newPassword, HttpSession session, Model model){
        User user = (User)session.getAttribute(Constants.USER_SESSION);
        boolean flag = false;

        // 判断attribute（user对象）不为空，且newpassword不为空
        if(user!=null && !StringUtils.isNullOrEmpty(newPassword)){
            // 更新数据库中的密码，返回是否成功的boolean值
            flag = userServiceImpl.updatePwd(user.getId(), newPassword);
            if(flag){
                model.addAttribute(Constants.MESSAGE,"修改密码成功，请退出，使用新密码登录!");
                // 密码修改成功，移除当前session
                session.removeAttribute(Constants.USER_SESSION);
            }else{
                model.addAttribute(Constants.MESSAGE,"密码修改失败！");
            }
        }else{
            model.addAttribute(Constants.MESSAGE,"新密码有问题！");
        }
        return "pwdModify";

    }
}
